// web/src/app/(auth)/settings/page.tsx
'use client';
import {useCurrentUser} from '@/hooks/use-current-user'
import React, {useState, useTransition} from 'react';
import {logout} from '@/actions/logout'
import {Card, CardContent, CardHeader} from "@/components/ui/card";
import {Button} from "@/components/ui/button";
import {settings} from "@/actions/settings";
import {useSession} from "next-auth/react";
import * as z from 'zod'
import {useForm} from "react-hook-form";
import {SettingsSchema} from "@/schemas";
import {zodResolver} from "@hookform/resolvers/zod";
import {Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage} from "@/components/ui/form";
import {Input} from "@/components/ui/input";
import FormError from "@/components/form-error";
import FormSuccess from "@/components/form-success";
import {Select, SelectContent, SelectItem, SelectTrigger, SelectValue} from "@/components/ui/select";
import {UserRole} from "@/lib/types";
import {Switch} from "@/components/ui/switch";

const Page = () => {
    const user = useCurrentUser()
    if (!user) return <div>loading...</div>

    const {update} = useSession()
    const [isPending, startTransition] = useTransition()

    // 提交表单后的错误或成功信息
    const [error, setError] = useState<string | undefined>('')
    const [success, setSuccess] = useState<string | undefined>('')

    const form = useForm<z.infer<typeof SettingsSchema>>({
        resolver: zodResolver(SettingsSchema),
        defaultValues: {
            password: undefined,
            newPassword: undefined,
            name: user?.name || undefined,
            email: user?.email || undefined,
            role: user?.role || undefined,
            isTwoFactorEnable: user?.isTwoFactorEnable || undefined,
        }
    })

    const onSubmit = (values: z.infer<typeof SettingsSchema>) => {
        startTransition(() => {
            setError('')
            setSuccess('')

            settings(values)
                .then((data) => {
                    // 修改后手动更新session信息
                    // 无效??? -> jwt回调修改
                    // update()
                    if (data.error) {
                        setError(data.error)
                    }
                    if (data.success) {
                        setSuccess(data.success)
                    }
                }).catch(() => setError('Something went wrong!'))
        })
    }

    return (
        <Card className={`w-[600px]`}>
            <CardHeader>
                <p className={`text-2xl font-semibold text-center`}>
                    Settings
                </p>
            </CardHeader>
            <CardContent>
                <Form {...form}>
                    <form
                        className={`space-y-6`}
                        onSubmit={form.handleSubmit(onSubmit)}
                    >
                        <div className={`space-y-4`}>
                            <FormField
                                control={form.control}
                                name={'name'}
                                render={({field}) => (
                                    <FormItem>
                                        <FormLabel>Name</FormLabel>
                                        <FormControl>
                                            <Input
                                                {...field}
                                                placeholder={'new name'}
                                                disabled={isPending}
                                            />
                                        </FormControl>
                                        <FormMessage/>
                                    </FormItem>
                                )}
                            />
                            {!user?.isOAuth && (
                                <>
                                    <FormField
                                        control={form.control}
                                        name={'email'}
                                        render={({field}) => (
                                            <FormItem>
                                                <FormLabel>Email</FormLabel>
                                                <FormControl>
                                                    <Input
                                                        {...field}
                                                        placeholder={'new email'}
                                                        disabled={isPending}
                                                        type="email"
                                                    />
                                                </FormControl>
                                                <FormMessage/>
                                            </FormItem>
                                        )}
                                    />
                                    <FormField
                                        control={form.control}
                                        name={'password'}
                                        render={({field}) => (
                                            <FormItem>
                                                <FormLabel>Old Password</FormLabel>
                                                <FormControl>
                                                    <Input
                                                        {...field}
                                                        placeholder={'******'}
                                                        disabled={isPending}
                                                        type="password"
                                                    />
                                                </FormControl>
                                                <FormMessage/>
                                            </FormItem>
                                        )}
                                    />
                                    <FormField
                                        control={form.control}
                                        name={'newPassword'}
                                        render={({field}) => (
                                            <FormItem>
                                                <FormLabel>New Password</FormLabel>
                                                <FormControl>
                                                    <Input
                                                        {...field}
                                                        placeholder={'******'}
                                                        disabled={isPending}
                                                        type="password"
                                                    />
                                                </FormControl>
                                                <FormMessage/>
                                            </FormItem>
                                        )}
                                    />
                                </>
                            )}
                            <FormField
                                control={form.control}
                                name={'role'}
                                render={({field}) => (
                                    <FormItem>
                                        <FormLabel>Role</FormLabel>
                                        <Select
                                            disabled={isPending}
                                            onValueChange={field.onChange}
                                            defaultValue={field.value}
                                        >
                                            <FormControl>
                                                <SelectTrigger>
                                                    <SelectValue placeholder={'Select a role'}/>
                                                </SelectTrigger>
                                            </FormControl>
                                            <SelectContent>
                                                <SelectItem value={UserRole.ADMIN}>
                                                    Admin
                                                </SelectItem>
                                                <SelectItem value={UserRole.USER}>
                                                    User
                                                </SelectItem>
                                            </SelectContent>
                                        </Select>
                                        <FormMessage/>
                                    </FormItem>
                                )}
                            />
                            {!user?.isOAuth && <FormField
                                control={form.control}
                                name={'isTwoFactorEnable'}
                                render={({field}) => (
                                    <FormItem className={`flex flex-row items-center justify-between
                                    rounded-lg border p-3 shadow-sm`}>
                                        <div className={`space-y-0.5`}>
                                            <FormLabel>Two Factor Authentication</FormLabel>
                                            <FormDescription>
                                                Enable two factor authentication for your account
                                            </FormDescription>
                                        </div>
                                        <FormControl>
                                            <Switch
                                                disabled={isPending}
                                                checked={field.value}
                                                onCheckedChange={field.onChange}
                                            />
                                        </FormControl>
                                    </FormItem>
                                )}
                            />}
                        </div>
                        <FormSuccess message={success}/>
                        <FormError message={error}/>
                        <Button
                            type={'submit'}
                        >
                            Save
                        </Button>
                    </form>
                </Form>
            </CardContent>
        </Card>
    );
};

export default Page;